package com.zsy.petshop_01.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zsy.petshop_01.dao.mapper.PetBaseInfoMapper;
import com.zsy.petshop_01.dao.mapper.PetCheckNumMapper;
import com.zsy.petshop_01.dao.mapper.PetCheckUserMapper;
import com.zsy.petshop_01.dao.mapper.PetTypeMapper;
import com.zsy.petshop_01.model.dto.ShowPetCheckNum;
import com.zsy.petshop_01.model.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class PetManager {
    @Autowired
    PetTypeMapper petTypeMapper;
    @Autowired
    PetBaseInfoMapper petBaseInfoMapper;
    @Autowired
    PetCheckNumMapper petCheckNumMapper;
    @Autowired
    PetCheckUserMapper petCheckUserMapper;

    public List<PetBaseInfo> selctAll() {
        return petBaseInfoMapper.selectList(null);
    }

    public void deletePet(Integer id) {
        petBaseInfoMapper.deleteById(id);
    }

    public void insetPet(PetBaseInfo petBaseInfo) {
        petBaseInfoMapper.insert(petBaseInfo);
    }

    public void updatePet(PetBaseInfo petBaseInfo) {
        petBaseInfoMapper.updateById(petBaseInfo);
    }

    public List<PetBaseInfo> selectPet(Integer age, String size, String type, Map<String, Integer> priceSection) {
        LambdaQueryWrapper<PetBaseInfo> petBaseInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (age != null) {
            petBaseInfoLambdaQueryWrapper.eq(PetBaseInfo::getPetAge, age);
        }
        if (type != null) {
            petBaseInfoLambdaQueryWrapper.eq(PetBaseInfo::getPetType, type);
        }
        if (size != null) {
            petBaseInfoLambdaQueryWrapper.eq(PetBaseInfo::getPetSize, size);
        }
        if (priceSection != null) {
            petBaseInfoLambdaQueryWrapper.ge(PetBaseInfo::getPetPrice, priceSection.get("min"));
            petBaseInfoLambdaQueryWrapper.le(PetBaseInfo::getPetPrice, priceSection.get("max"));
        }
        return petBaseInfoMapper.selectList(petBaseInfoLambdaQueryWrapper);
    }

    public List<PetBaseInfo> changeType(List<PetBaseInfo> petBaseInfoList) {
        List<PetBaseInfo> petsResult = new ArrayList<>();
        for (PetBaseInfo petBaseInfo : petBaseInfoList) {
            Integer petType = Integer.parseInt(petBaseInfo.getPetType());
            LambdaQueryWrapper<PetType> typeWrapper = new LambdaQueryWrapper<>();
            typeWrapper.eq(PetType::getPetNum, petType);
            petBaseInfo.setPetType(petTypeMapper.selectOne(typeWrapper).getPetType().toString());
            petsResult.add(petBaseInfo);
        }
        return petsResult;
    }

    public void upvote(Integer id) {
        PetBaseInfo petBaseInfo = petBaseInfoMapper.selectById(id);
        petBaseInfo.setPetUpvote(petBaseInfo.getPetUpvote() + 1);
        petBaseInfoMapper.updateById(petBaseInfo);
    }

    public void downVote(Integer id) {
        PetBaseInfo petBaseInfo = petBaseInfoMapper.selectById(id);
        petBaseInfo.setPetUpvote(petBaseInfo.getPetUpvote() - 1);
        petBaseInfoMapper.updateById(petBaseInfo);
    }

    public List<PetType> selectPetType() {
        return petTypeMapper.selectList(null);
    }

    public void insertPetType(PetType petType) {
        petTypeMapper.insert(petType);
    }

    public void updatePetType(Integer id, String petType) {
        PetType petType1 = petTypeMapper.selectById(id);
        petType1.setPetType(petType);
        petTypeMapper.updateById(petType1);
    }

    public void deletePetType(Integer id) {
        petTypeMapper.deleteById(id);
    }

    public List<ShowPetCheckNum> selectPetCheck() {
        List<ShowPetCheckNum> result = new ArrayList<>();
        List<PetCheckNum> petCheckNums = petCheckNumMapper.selectList(null);
        for (PetCheckNum petCheckNum : petCheckNums) {
            Integer checkNum = petCheckNum.getCheckNum();
            Integer checkNumId = petCheckNum.getId();

            LambdaQueryWrapper<PetCheckUser> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(PetCheckUser::getCheckId, checkNumId);
            List<PetCheckUser> petCheckUsers = petCheckUserMapper.selectList(wrapper1);
            int sum = petCheckUsers.stream()
                    .filter(p -> p.getPetNum() != null) // 如果 PetNum 是对象类型，过滤 null
                    .mapToInt(PetCheckUser::getPetNum)  // 转换为 int 流（自动拆箱）
                    .sum();

            ShowPetCheckNum showPetCheckNum = new ShowPetCheckNum();
            showPetCheckNum.setCheckNum(checkNum - sum);
            showPetCheckNum.setPetCheckId(checkNumId);
            showPetCheckNum.setDate(petCheckNum.getDate());
            result.add(showPetCheckNum);
        }
        return result;
    }

    public String subscribeCheck(List<Integer> checkIds, Integer petNum, Integer userId) {
        for (Integer checkId : checkIds) {
            if (petCheckNumMapper.selectById(checkId).getCheckNum() < petNum) {
                return ("剩余数量不足，无法预约");
            }
            if (petCheckUserMapper.selectOne(new LambdaQueryWrapper<PetCheckUser>().eq(PetCheckUser::getCheckId, checkId).eq(PetCheckUser::getUserId,userId)) != null) {
                return ("您已预约，请勿重复预约");
            }
            PetCheckUser petCheckUser = new PetCheckUser();
            petCheckUser.setCheckId(checkId);
            petCheckUser.setPetNum(petNum);
            petCheckUser.setUserId(userId);
            petCheckUserMapper.insert(petCheckUser);
        }
        return "Success";
    }

    public void cancelSubscribeCheck(Integer id) {
        petCheckUserMapper.deleteById(id);
    }

    public List<PetCheckUser> selectAllCheck() {
        return petCheckUserMapper.selectList(null);
    }

    public List<PetCheckUser> selectCheckByUser(Integer userId) {
        LambdaQueryWrapper<PetCheckUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PetCheckUser::getUserId, userId);
        return petCheckUserMapper.selectList(wrapper);
    }

    public void updateCheckMaxNum(Integer id, Integer maxNum) {
        LambdaUpdateWrapper<PetCheckNum> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(PetCheckNum::getId, id)
                .set(PetCheckNum::getCheckNum, maxNum);
        petCheckNumMapper.update(null, wrapper);
    }

    public void createCheckSevenDays(LocalDate time) {
        // 指定中国时区（东八区，Asia/Shanghai）
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        for (int i = 0; i < 7; i++) {
            // 将 LocalDate 转换为中国时区的 LocalDateTime 并设置为当天 0 点
            LocalDateTime midnight = LocalDateTime.of(time, LocalTime.MIN).atZone(zoneId).toLocalDateTime();
            // 将 0 点时间转换为毫秒时间戳
            long epochMilli = midnight.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

            PetCheckNum petCheckNum = new PetCheckNum();
            LambdaQueryWrapper<PetCheckNum> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PetCheckNum::getDate, String.valueOf(epochMilli));
            PetCheckNum petCheckNum1 = petCheckNumMapper.selectOne(wrapper);
            if (petCheckNum1 != null) {
                time = time.plusDays(1);
                continue;
            }
            petCheckNum.setDate(String.valueOf(epochMilli));
            petCheckNum.setCheckNum(20);
            petCheckNumMapper.insert(petCheckNum);
            time = time.plusDays(1);
        }
    }
}
